package com.freewater.springboot.demo.conversion.converter;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        final ConversionService conversionService = new DefaultConversionService();
        // 内部使用IdToEntityConverter转换
        final Account account = conversionService.convert("123", Account.class);
        System.out.println(account);
        // 指定复杂的类型转换
        final List<String> strlist = new ArrayList<>();
        strlist.add("123");
        strlist.add("456");
        strlist.add("789");
        TypeDescriptor sourceType = TypeDescriptor.forObject(strlist);
        TypeDescriptor targetType = TypeDescriptor.collection(ArrayList.class, TypeDescriptor.valueOf(Integer.class));
        final List<Integer> intList = (List<Integer>) conversionService.convert(strlist, sourceType, targetType);
        System.out.println(intList);
    }

    public static final class Account {

        private final String id;

        private final String name;

        public Account(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public static Account findAccount(String id) {
            return new Account(id, "account " + id);
        }

        @Override
        public String toString() {
            return "Account{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}
